// learning.js - 单词学习页面逻辑
const WordLearningService = require('./services/wordLearningService');
const { showSuccessToast, showErrorToast, calculateProgressPercentage } = require('./utils/learningUtils');
const storageManager = require('../../../manager/storageManager').getInstance();

Page({
  data: {
    unitName: '单元学习',
    currentWordIndex: 1,
    totalWordsCount: 0,
    learnedCount: 0,
    currentWord: {
      english: '',
      phonetic: '',
      chinese: '',
      example: ''
    },
    learningProgress: 0,
    wordExamples: [],
    showExamplesModal: false,
    isListenMode: false,
    isWriteMode: false,
    studyTime: '0分钟',
    accuracy: 0,
    showCompleteModal: false,
    studyStartTime: 0,
    words: [],
    // 发音设置
    pronunciationType: 'american',
    playbackSpeed: 1.0,
    autoPlay: true,
    // 音频状态
    isPlaying: false
  },

  onLoad: function(options) {
    // 获取全局应用实例
    this.app = getApp();
    
    // 初始化服务
    this.initServices();
    
    // 初始化学习时间
    this.setData({
      studyStartTime: new Date().getTime(),
      unitName: options.unitName || '单元学习'
    });

    // 保存startWordId参数
    this.startWordId = options.startWordId;

    // 加载发音设置
    this.loadPronunciationSettings();

    // 加载单词数据
    this.loadWordsData();
  },

  /**
   * 初始化服务
   */
  initServices: function() {
    this.wordLearningService = new WordLearningService();
    this.wordLearningService.init();
    
    // 获取全局AudioManager实例
    this.audioManager = this.app.getAudioManager();
    
    // 添加音频状态变化回调
    this.audioManager.addStatusChangeCallback(this.onAudioStatusChange.bind(this));
  },

  /**
   * 音频状态变化回调函数
   */
  onAudioStatusChange: function(status) {
    this.setData({
      isPlaying: status.isPlaying
    });
  },

  /**
   * 加载单词数据
   */
  loadWordsData: function() {
    this.wordLearningService.loadWordsData(this.startWordId)
      .then(result => {
        const currentIndex = result.startIndex || 1;
        const learningProgress = calculateProgressPercentage(currentIndex, result.words.length);
        
        this.setData({
          words: result.words,
          totalWordsCount: result.words.length,
          currentWord: result.currentWord,
          currentWordIndex: currentIndex,
          learningProgress,
          unitName: result.unitName
        });

        // 更新当前单词的学习次数和最新学习时间
        if (result.currentWord && result.currentWord.id) {
          try {
            // 获取全局数据管理器实例
            const app = getApp();
            const dm = app.globalData.wordDataManager;
            
            // 使用API增加学习次数，不再直接操作learningInfo
            dm.incrementWordLearnCount(result.currentWord.id);
          } catch (error) {
            console.error('更新单词学习数据失败:', error);
          }
        }

        // 如果开启了自动播放，延迟播放当前单词的发音
        if (this.data.autoPlay && result.words.length > 0) {
          setTimeout(() => {
            this.playPronunciation();
          }, 500); // 延迟500ms，给页面加载一点时间
        }
      })
      .catch(error => {
        console.error('加载单词数据失败:', error);
        showErrorToast(error.message || '加载单词数据失败，请稍后重试');
        
        // 延迟返回，提示用户
        setTimeout(() => {
          wx.navigateBack();
        }, 3000);
      });
  },

  /**
   * 加载发音设置
   */
  loadPronunciationSettings: function() {
    try {
      const settings = this.wordLearningService.loadPronunciationSettings();
      
      this.setData({
        pronunciationType: settings.pronunciationType || 'american',
        playbackSpeed: settings.playbackSpeed || 1.0,
        autoPlay: settings.autoPlay !== undefined ? settings.autoPlay : true,
        loopPlay: settings.loopPlay || false,
        loopCount: settings.loopCount || '',
        loopInterval: settings.loopInterval || 2
      });
      
      // 将循环设置应用到音频管理器
      if (this.audioManager) {
        this.audioManager.setLoopSettings(
          this.data.loopPlay,
          this.data.loopCount,
          this.data.loopInterval
        );
      }
    } catch (error) {
      console.error('加载发音设置失败:', error);
    }
  },

  /**
   * 设置变更处理方法
   */
  onSettingChange: function(e) {
    const { type, value } = e.detail;
    // 更新设置
    this.setData({
      [type]: value
    });
    // 如果是发音相关设置变更，重新播放当前单词发音
    if (['pronunciationType', 'playbackSpeed', 'loopPlay', 'loopCount', 'loopInterval'].includes(type)) {
      this.playPronunciation();
    }
    
    const success = this.wordLearningService.savePronunciationSetting(type, value);
    
    if (success) {
      // 根据类型更新UI状态
      switch(type) {
        case 'pronunciationType':
          this.setData({ pronunciationType: value });
          showSuccessToast(`已切换到${value === 'american' ? '美式' : '英式'}发音`);
          break;
        case 'playbackSpeed':
          // 验证倍速范围，并保留两位小数
          const validSpeed = Math.round(Math.max(0.5, Math.min(2.0, parseFloat(value))) * 100) / 100;
          this.setData({
            playbackSpeed: validSpeed
          });
          showSuccessToast(`已设置${validSpeed}x倍速`);
          break;
        case 'autoPlay':
          this.setData({ autoPlay: value });
          showSuccessToast(value ? '已开启自动播放' : '已关闭自动播放');
          break;
        case 'loopPlay':
          this.setData({ loopPlay: value });
          if (this.audioManager) {
            this.audioManager.setLoopSettings(
              value,
              this.data.loopCount,
              this.data.loopInterval
            );
          }
          showSuccessToast(value ? '已开启循环播放' : '已关闭循环播放');
          break;
        case 'loopCount':
          this.setData({ loopCount: value });
          if (this.audioManager) {
            this.audioManager.setLoopSettings(
              this.data.loopPlay,
              value,
              this.data.loopInterval
            );
          }
          showSuccessToast(`已设置循环次数为${value || '无限'}`);
          break;
        case 'loopInterval':
          this.setData({ loopInterval: value });
          if (this.audioManager) {
            this.audioManager.setLoopSettings(
              this.data.loopPlay,
              this.data.loopCount,
              value
            );
          }
          showSuccessToast(`已设置循环间隔为${value}秒`);
          break;
      }
    }
  },

  /**
   * 播放发音
   */
  playPronunciation: function() {
    const { playbackSpeed, pronunciationType, currentWord, loopPlay, loopCount, loopInterval } = this.data;

    if (!currentWord || !currentWord.english) {
      showErrorToast('当前没有单词可播放');
      return;
    }

    // 应用当前的循环设置
    if (this.audioManager) {
      this.audioManager.setLoopSettings(loopPlay, loopCount, loopInterval);
    }

    // 现在直接传入单词对象，让audioManager内部处理音频URL获取和错误处理
    this.audioManager.playPronunciation(currentWord, playbackSpeed, pronunciationType)
      .then(() => {
        this.updateAudioStatus();
      })
      .catch(error => {
        console.error('播放失败:', error);
        showErrorToast('播放失败');
        this.updateAudioStatus();
      });
  },

  /**
   * 停止发音播放
   */
  stopPronunciation: function() {
    this.audioManager.stopPronunciation();
    this.updateAudioStatus();
  },



  /**
   * 更新音频状态到UI
   */
  updateAudioStatus: function() {
    const status = this.audioManager.getStatus();
    this.setData({
      isPlaying: status.isPlaying
    });
  },

  /**
   * 显示更多例句
   */
  showMoreExamples: function() {
    const examples = this.data.currentWord.examples || [];
    this.setData({
      wordExamples: examples,
      showExamplesModal: true
    });
  },

  /**
   * 关闭例句弹窗
   */
  closeExamplesModal: function() {
    this.setData({
      showExamplesModal: false
    });
  },

  /**
   * 进入听单词模式
   */
  listenWord: function() {
    this.setData({
      isListenMode: true
    });
  },

  /**
   * 进入写单词模式
   */
  writeWord: function() {
    this.setData({
      isWriteMode: true,
      writtenWord: '',
      showWriteResult: false,
      writeResultText: ''
    });
  },

  /**
   * 测试模式
   */
  testWord: function() {
    showErrorToast('测试模式');
  },

  /**
   * 切换到上一个单词
   */
  previousWord: function() {
    if (this.data.currentWordIndex > 1) {
      const newIndex = this.data.currentWordIndex - 1;
      const newWord = this.data.words[newIndex - 1];
      const learningProgress = calculateProgressPercentage(newIndex, this.data.words.length);

      this.setData({
        currentWordIndex: newIndex,
        currentWord: newWord,
        learningProgress
      });

      // 同步上一个单词数据
      if (newWord && newWord.id) {
        const app = getApp();
        const dm = app.globalData.wordDataManager;
        dm.enrichWords([newWord.id], {
          onProgress: () => {
            this.setData({
              isLoadingSync: true
            });
          },
          onComplete: () => {
            console.log('上一个单词同步成功');
            // 获取最新的单词数据
            const updatedWord = dm.getWordById(newWord.id);
            if (updatedWord) {
              // 更新单词数据
              const updatedWords = [...this.data.words];
              updatedWords[newIndex - 1] = updatedWord;
              this.setData({
                words: updatedWords,
                currentWord: updatedWord,
                isLoadingSync: false
              });
            } else {
              this.setData({
                isLoadingSync: false
              });
            }
          },
          onError: (error) => {
            console.log('上一个单词同步失败:', error);
            this.setData({
              isLoadingSync: false
            });
          }
        });
      }

      // 如果开启了自动播放，则自动播放发音
      if (this.data.autoPlay && this.data.words.length > 0) {
        setTimeout(() => {
          this.playPronunciation();
        }, 300);
      }
    }
  },

  /**
   * 切换到下一个单词
   */
  nextWord: function() {
    if (this.data.currentWordIndex < this.data.words.length) {
      const newIndex = this.data.currentWordIndex + 1;
      const newWord = this.data.words[newIndex - 1];
      const learningProgress = calculateProgressPercentage(newIndex, this.data.words.length);

      this.setData({
        currentWordIndex: newIndex,
        currentWord: newWord,
        learningProgress
      });

      // 同步下一个单词数据
      if (newWord && newWord.id) {
        const app = getApp();
        const dm = app.globalData.wordDataManager;
        dm.enrichWords([newWord.id], {
          onProgress: () => {
            this.setData({
              isLoadingSync: true
            });
          },
          onComplete: () => {
            console.log('下一个单词同步成功');
            // 获取最新的单词数据
            const updatedWord = dm.getWordById(newWord.id);
            if (updatedWord) {
              // 更新单词数据
              const updatedWords = [...this.data.words];
              updatedWords[newIndex - 1] = updatedWord;
              this.setData({
                words: updatedWords,
                currentWord: updatedWord,
                isLoadingSync: false
              });
            } else {
              this.setData({
                isLoadingSync: false
              });
            }
            
            // 单词数据同步完成后，如果开启了自动播放，则自动播放发音
            if (this.data.autoPlay && updatedWord) {
              setTimeout(() => {
                this.playPronunciation();
              }, 300);
            }
          },
          onError: (error) => {
            console.log('下一个单词同步失败:', error);
            this.setData({
              isLoadingSync: false
            });
            
            // 即使同步失败，仍然尝试播放发音
            if (this.data.autoPlay) {
              setTimeout(() => {
                this.playPronunciation();
              }, 300);
            }
          }
        });
      } else if (this.data.autoPlay) {
        // 如果没有需要同步的数据，直接播放发音
        setTimeout(() => {
          this.playPronunciation();
        }, 300);
      }
    } else {
      // 如果已经是最后一个单词，显示学习完成弹窗
      this.showCompleteModal();
    }
  },

  /**
   * 标记当前单词的记忆状态
   */
  markAsMemorized: function() {
    const { currentWordIndex, words } = this.data;
    const currentIndex = currentWordIndex - 1;
    const currentWord = words[currentIndex];

    try {
      // 获取全局数据管理器实例
      const app = getApp();
      const dm = app.globalData.wordDataManager;
      
      // 获取当前记忆状态
      const currentMemorized = dm.getWordMemorizedStatus(currentWord.id);
      const newIsMemorized = !currentMemorized;
      
      const success = dm.setWordMemorizedStatus(currentWord.id, newIsMemorized);

      if (success) {
        // 更新本地数据状态，不再使用learningInfo
        const updatedWords = [...words];
        updatedWords[currentIndex] = {
          ...updatedWords[currentIndex],
          isMemorized: newIsMemorized
        };
        
        this.setData({
          words: updatedWords,
          currentWord: updatedWords[currentIndex]
        });

        // 显示操作成功提示
        wx.showToast({
          title: newIsMemorized ? '已标记为记住' : '已取消记住',
          icon: 'none'
        });

        // 如果标记为记住，更新今日新学习单词任务数据
        if (newIsMemorized) {
          this._updateTodayTaskData('new');
        }
      } else {
        showErrorToast('标记失败，请重试');
      }
    } catch (error) {
      console.error('设置单词记忆状态失败:', error);
      showErrorToast('操作失败，请重试');
    }
  },

  /**
   * 听力模式完成回调
   */
  onListenComplete: function(e) {
    const { result, word } = e.detail;
    this.setData({
      isListenMode: false
    });
  },

  /**
   * 退出听力模式
   */
  exitListenMode: function() {
    this.setData({
      isListenMode: false
    });
  },

  /**
   * 退出书写模式
   */
  exitWriteMode: function() {
    this.setData({
      isWriteMode: false
    });
  },

  /**
   * 显示学习完成弹窗
   */
  showCompleteModal: function() {
    // 计算学习统计数据
    const stats = this.wordLearningService.calculateLearningStats(this.data.studyStartTime);
    
    this.setData({
      studyTime: stats.studyTime,
      accuracy: stats.accuracy,
      showCompleteModal: true
    });
  },

  /**
   * 复习单元
   */
  reviewUnit: function() {
    this.setData({
      showCompleteModal: false,
      currentWordIndex: 1,
      currentWord: this.data.words[0],
      learningProgress: 0,
      studyStartTime: new Date().getTime()
    });
  },

  /**
   * 单元测试
   */
  takeUnitTest: function() {
    showErrorToast('即将开始单元测试');
  },

  /**
   * 返回单元详情
   */
  backToUnitDetail: function() {
    wx.navigateBack();
  },

  /**
   * 学习控制组件事件处理函数
   */
  
  /**
   * 处理单词数据更新事件
   */
  onWordUpdated: function(e) {
    const { word } = e.detail;
    if (word) {
      // 更新currentWord数据，这会自动同步到word-display组件
      this.setData({
        currentWord: word
      });
    }
  },
  
  /**
   * 切换设置面板的展开状态
   */
  onToggleSettings: function() {
    // 获取learning-settings组件实例
    const settingsComponent = this.selectComponent('#learningSettings');
    if (settingsComponent) {
      // 调用组件的toggleSettingsPanel方法
      settingsComponent.toggleSettingsPanel();
    }
  },
  
  onPlayStart: function() {
    // 当组件触发开始播放事件时，调用audioManager播放音频
    this.playPronunciation();
  },
  
  onPlayEnd: function() {
    // 当组件播放音频结束时触发，通过audioManager的状态更新
    this.updateAudioStatus();
  },
  
  onStopPlay: function() {
    // 当组件触发停止播放事件时，调用audioManager停止音频
    this.stopPronunciation();
  },

  /**
   * 页面卸载时清理资源
   */
  onUnload: function() {
    // 更新全局学习数据
    this.wordLearningService.updateGlobalLearningData();

    // 移除音频状态变化回调
    if (this.audioManager) {
      this.audioManager.removeStatusChangeCallback(this.onAudioStatusChange.bind(this));
    }
    
    // 保存当前词书/分类信息，以便返回word-list页面时可以更新对应单词的学习次数
    try {
      const currentBook = this.wordLearningService.getCurrentBook();
      if (currentBook && this.data.currentWord && this.data.currentWord.id) {
        storageManager.setStorage(storageManager.STORAGE_KEYS.LAST_LEARNED_WORD_INFO, {
          wordId: this.data.currentWord.id,
          sourceType: 'book',
          sourceId: currentBook.id
        });
      } else if (this.data.sourceCategory && this.data.currentWord && this.data.currentWord.id) {
        storageManager.setStorage(storageManager.STORAGE_KEYS.LAST_LEARNED_WORD_INFO, {
          wordId: this.data.currentWord.id,
          sourceType: 'category',
          sourceId: this.data.sourceCategory
        });
      }
    } catch (error) {
      console.error('保存学习信息失败:', error);
    }
  },
  
  /**
   * 更新今日任务数据
   * @param {string} taskType - 任务类型 ('new' 或 'review')
   */
  _updateTodayTaskData: function(taskType) {
    try {
      // 获取当前词书信息
      const currentBook = this.wordLearningService.getCurrentBook();
      if (!currentBook) {
        console.warn('未找到当前词书信息');
        return;
      }
      
      // 获取今日任务组件实例
      const app = getApp();
      if (app.globalData.todayTasksComponent && app.globalData.todayTasksComponent.refreshTasks) {
        // 刷新今日任务数据
        app.globalData.todayTasksComponent.refreshTasks();
      } else {
        console.log('今日任务组件未初始化，稍后会自动更新');
        // 记录学习事件到本地存储，方便任务组件加载时识别
        const learningEvents = storageManager.getStorage(storageManager.STORAGE_KEYS.TODAY_LEARNING_EVENTS) || [];
        learningEvents.push({
          type: taskType,
          bookId: currentBook.id,
          wordId: this.data.currentWord ? this.data.currentWord.id : null,
          timestamp: new Date().toISOString()
        });
        storageManager.setStorage(storageManager.STORAGE_KEYS.TODAY_LEARNING_EVENTS, learningEvents);
      }
    } catch (error) {
      console.error('更新今日任务数据失败:', error);
    }
  }
});